package com.xu.cloud.common.advice;

import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.desensitization.Desensitization;
import com.xu.cloud.common.desensitization.DesensitizationHandler;
import com.xu.cloud.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Field;

/**
 * 返回值脱敏后置通知处理器
 *
 * @author xuguan
 * @see Result
 * @since 2023/4/15
 */
@Order(OrderConstant.DESENSITIZATION_RESPONSE_BODY_ADVICE_ORDER)
@Slf4j
@RestControllerAdvice(basePackages = {"com.xu"})
public class DesensitizationResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final DesensitizationHandler desensitizationHandler;

    public DesensitizationResponseBodyAdvice(DesensitizationHandler desensitizationHandler) {
        this.desensitizationHandler = desensitizationHandler;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        final Class<?> cls = returnType.getParameterType();
        final Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (AnnotatedElementUtils.hasAnnotation(field, Desensitization.class)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        desensitizationHandler.desensitization(body);
        return body;
    }
}
